import { FC, useEffect, useRef } from "react";
import { Loading } from "react-vant";
import styles from "./index.module.scss";
interface IPros {
  root?: Element | null;
  isLoading: boolean;
  more(): void;
}
const LoadMore: FC<IPros> = (props) => {
  const { root, isLoading, more } = props;
  const loadMoreRef = useRef<HTMLDivElement | null>();
  const loadMoreFun = () => {
    if (!loadMoreRef.current) {
      return;
    }
    const ob = new IntersectionObserver(
      (entries) => {
        const [entry] = entries;
        // 有重叠，并且没有在请求
        if (entry.isIntersecting && !isLoading) {
          more();
        }
      },
      {
        root,
        threshold: 1,
      }
    );
    ob.observe(loadMoreRef.current);
  };
  useEffect(() => {
    loadMoreFun();
    return () => {};
  }, []);
  if (isLoading) {
    return null;
  }
  return (
    <div
      className={styles.loadMoreWrap}
      ref={(ref) => (loadMoreRef.current = ref)}
    >
      <Loading color="red" />
    </div>
  );
};

export default LoadMore;
